<template>
  <div class="carousel-container">
    <el-card class="carousel-card">
      <template #header>
        <div class="card-header">
          <h2>轮播图管理</h2>
          <el-button type="primary" @click="openUploadDialog">
            <el-icon><Plus /></el-icon>
            添加轮播图
          </el-button>
        </div>
      </template>

      <!-- 轮播图列表 -->
      <div v-loading="loading">
        <el-empty v-if="carouselList.length === 0" description="暂无轮播图数据" />
        
        <el-row :gutter="20" v-else>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in carouselList" :key="item.id" class="carousel-item-col">
            <el-card class="carousel-item" shadow="hover">
              <div class="image-container">
                <el-image 
                  :src="getFullImageUrl(item.imageUrl)" 
                  fit="cover"
                  :preview-src-list="[getFullImageUrl(item.imageUrl)]"
                  preview-teleported
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <span>加载失败</span>
                    </div>
                  </template>
                </el-image>
              </div>
              <div class="carousel-info">
                <div class="carousel-description">{{ item.description || '暂无描述' }}</div>
                <div class="carousel-actions">
                  <el-popconfirm
                    title="确定要删除这张轮播图吗？"
                    @confirm="handleDelete(item.id)"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                  >
                    <template #reference>
                      <el-button type="danger" size="small" text>
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 上传轮播图对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传轮播图"
      width="500px"
      destroy-on-close
    >
      <el-form :model="uploadForm" :rules="rules" ref="uploadFormRef" label-width="80px">
        <el-form-item label="轮播图" prop="image">
          <el-upload
            class="carousel-upload"
            :auto-upload="false"
            :limit="1"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :on-exceed="handleExceed"
            accept="image/jpeg,image/png,image/gif"
            list-type="picture-card"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">请上传JPG/PNG格式图片，建议尺寸为 750x350 像素</div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="uploadForm.description" placeholder="请输入轮播图描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">上传</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Picture } from '@element-plus/icons-vue'
import axios from 'axios'
import { useUserStore } from '../../store/user'

const userStore = useUserStore()

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 10000
})

// 数据状态
const loading = ref(false)
const carouselList = ref([])
const uploadDialogVisible = ref(false)
const uploading = ref(false)
const uploadFormRef = ref(null)

// 上传表单
const uploadForm = reactive({
  description: '',
  image: null
})

// 表单验证规则
const rules = {
  description: [
    { required: true, message: '请输入轮播图描述', trigger: 'blur' },
    { max: 50, message: '描述不能超过50个字符', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传轮播图图片', trigger: 'change' }
  ]
}

// 获取完整图片URL
const getFullImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `http://localhost:3000${url}`
}

// 获取轮播图列表
const fetchCarouselList = async () => {
  if (!userStore.token) {
    ElMessage.error('您尚未登录或登录已过期，请重新登录')
    return
  }

  loading.value = true
  try {
    const response = await api.get('/api/carousel', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })
    carouselList.value = response.data
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      userStore.logout()
    } else {
      ElMessage.error(error.response?.data?.message || '获取轮播图列表失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 打开上传对话框
const openUploadDialog = () => {
  uploadDialogVisible.value = true
  uploadForm.description = ''
  uploadForm.image = null
}

// 处理图片选择
const handleImageChange = (file) => {
  // 验证图片类型
  const isImage = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png' || file.raw.type === 'image/gif'
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!')
    return false
  }
  
  // 验证图片大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  
  uploadForm.image = file.raw
  return true
}

// 处理图片移除
const handleImageRemove = () => {
  uploadForm.image = null
}

// 处理超出上传数量限制
const handleExceed = () => {
  ElMessage.warning('只能上传一张图片')
}

// 提交上传
const submitUpload = async () => {
  if (!userStore.token) {
    ElMessage.error('您尚未登录或登录已过期，请重新登录')
    return
  }

  uploadFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error('请正确填写表单内容')
      return
    }

    if (!uploadForm.image) {
      ElMessage.error('请选择要上传的图片')
      return
    }

    uploading.value = true
    try {
      // 创建FormData对象
      const formData = new FormData()
      formData.append('image', uploadForm.image)
      formData.append('description', uploadForm.description)

      // 发送上传请求
      await api.post('/api/carousel', formData, {
        headers: {
          'Authorization': `Bearer ${userStore.token}`,
          'Content-Type': 'multipart/form-data'
        }
      })

      ElMessage.success('轮播图上传成功')
      uploadDialogVisible.value = false
      fetchCarouselList() // 刷新列表
    } catch (error) {
      console.error('上传轮播图失败:', error)
      if (error.response && error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        userStore.logout()
      } else {
        ElMessage.error(error.response?.data?.message || '上传轮播图失败，请稍后重试')
      }
    } finally {
      uploading.value = false
    }
  })
}

// 删除轮播图
const handleDelete = async (id) => {
  if (!userStore.token) {
    ElMessage.error('您尚未登录或登录已过期，请重新登录')
    return
  }

  try {
    await api.delete(`/api/carousel/${id}`, {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })
    
    ElMessage.success('轮播图删除成功')
    fetchCarouselList() // 刷新列表
  } catch (error) {
    console.error('删除轮播图失败:', error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      userStore.logout()
    } else {
      ElMessage.error(error.response?.data?.message || '删除轮播图失败，请稍后重试')
    }
  }
}

// 初始化
onMounted(() => {
  fetchCarouselList()
})
</script>

<style scoped>
.carousel-container {
  padding: 20px;
}

.carousel-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #303133;
}

.carousel-item-col {
  margin-bottom: 20px;
}

.carousel-item {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.image-container {
  width: 100%;
  height: 180px;
  overflow: hidden;
  border-radius: 4px;
  margin-bottom: 10px;
}

.el-image {
  width: 100%;
  height: 100%;
  transition: transform 0.3s;
}

.el-image:hover {
  transform: scale(1.05);
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  background-color: #f5f7fa;
}

.carousel-info {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1;
}

.carousel-description {
  margin-bottom: 10px;
  color: #606266;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.carousel-actions {
  display: flex;
  justify-content: flex-end;
}

.carousel-upload .el-upload--picture-card {
  width: 200px;
  height: 120px;
  line-height: 120px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>